package com.minisoft.gateway;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.minisoft.utils.HttpClientService;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public class AutoAuthorizationHutool {

    /**
     * 主要替换下面4个变量
     */
    private static String PROFILE = "test";//dev/test/pre/pro
    private static final String COOKIE = "_ga=GA1.2.666367604.1700011752; oam_locale=zh; mx-languale=zh_CN; mip_curr_lang=zh-CN; user_info=%7B%22fdPositiontype%22%3A%22%22%2C%22id%22%3A%22u_32313%22%2C%22parentId%22%3A%22d_7955%22%2C%22name%22%3A%22%E9%99%88%E7%8F%8F%E8%B0%A1%22%2C%22fdLangType%22%3A%22zh-CN%22%2C%22fdPositionName%22%3A%22%E7%B3%BB%E7%BB%9F%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88%22%2C%22fdEmail%22%3A%22chenjuesu%40huafagroup.com%22%2C%22loginName%22%3A%22chenjuesu%22%2C%22fdEnglishName%22%3A%22%22%2C%22fdTimeZone%22%3A%22Asia%2FChongqing%22%2C%22fdEmployeeNumber%22%3A%2218037415%22%2C%22fdDepartmentEnglishName%22%3A%22%22%2C%22fdDepartmentName%22%3A%22%E5%8D%8E%E5%8F%91%E9%9B%86%E5%9B%A2_%E9%9B%86%E5%9B%A2%E7%9B%B4%E7%AE%A1%E4%B8%9A%E5%8A%A1_%E5%8D%8E%E5%8F%91%E6%95%B0%E6%99%BA_%E5%88%9B%E6%96%B0%E7%A0%94%E5%8F%91%E9%83%A8_%E5%BC%80%E5%8F%91%E4%B8%80%E7%BB%84%22%2C%22fdHierarchyId%22%3A%22x2x107x3079x3081x7955x32313x%22%2C%22shiroid%22%3A%22b5ac50a7-a118-4b53-8026-3d8910c9c7ba%22%7D; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22fengweilong%22%2C%22first_id%22%3A%22183d560f02110ea-035a3fe9867f1f4-576153e-921600-183d560f022f96%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTgzZDU2MGYwMjExMGVhLTAzNWEzZmU5ODY3ZjFmNC01NzYxNTNlLTkyMTYwMC0xODNkNTYwZjAyMmY5NiIsIiRpZGVudGl0eV9sb2dpbl9pZCI6ImZlbmd3ZWlsb25nIn0%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22fengweilong%22%7D%2C%22%24device_id%22%3A%22183d560f02110ea-035a3fe9867f1f4-576153e-921600-183d560f022f96%22%7D; JSESSIONID=ZjQ3OGM4MzQtODZlOC00OWU3LTliMjUtOTJkOGU3ZTQwMzUx";
    private static String APPID = "huafa-market";
        private static String SERVICEID = "gf-interaction-center-service";
//    private static String SERVICEID = "gf-interaction-center-service-test";
//    private static String SERVICEID = "gf-interaction-center-service-pre";
    //    private static String SERVICEID = "gf-interaction-center-service";
//    private static String SERVICEID = "gf-customer-center-service";
//    private static String SERVICEID = "gf-customer-center-service-test";
//    private static String SERVICEID = "gf-customer-center-service-pre";
//    private static String SERVICEID = "gf-customer-center-service-pro";
//    private static String SERVICEID = "gf-market-permit-service";
//    private static String SERVICEID = "gf-market-permit-service-test";
//    private static String SERVICEID = "gf-market-permit-service-pre";
//    private static String SERVICEID = "gf-market-permit-service";
//    private static String SERVICEID = "gf-cnhuafas-customer-pool";
//    private static String SERVICEID = "gf-cnhuafas-customer-pool-test";
//    private static String SERVICEID = "gf-cnhuafas-customer-pool-pre";
//    private static String SERVICEID = "gf-cnhuafas-customer-pool-pro";
//    private static String SERVICEID = "gf-base-auth-service-pre";
//    private static String SERVICEID = "gf-base-auth-service-pro";
    static Map<String, String> HOST_MAP = new HashMap<>();
    private static final String GET_AUTHORIZED_API_LIST_PATH = "/privilege/getApiListByApp";
    private static final String GET_SERVICE_API_LIST_PATH = "/gateway/api/getListByApplicationSelected";
    private static final String AUTHORIZE_APIS_PATH = "/privilege/updateList";

    static {
        HOST_MAP.put("dev", "http://apiadmin.paasdev.huafagroup.com");
        HOST_MAP.put("test", "http://apiadmin.paasdev4.huafagroup.com");
        HOST_MAP.put("pre", "http://apiadmin.paas.huafagroup.com");
        HOST_MAP.put("pro", "http://apiadmin.paas.huafagroup.com");
    }
    public static void main(String[] args) {
        // Step 1: 获取已授权接口列表
        JSONArray authorizedApiList = getAuthorizedApiList(APPID);
        log.info("已授权接口列表个数：{}" , authorizedApiList.size());
        //转成Map
        Map<String, Object> authorizedApiMap = authorizedApiList.stream().filter(item -> ((JSONObject)item).getStr("serviceId").equals(SERVICEID)).collect(Collectors.toMap(item -> ((JSONObject)item).getStr("path"), Function.identity(), (v1, v2) -> v1));

        // Step 2: 获取指定服务的接口列表
        JSONArray specifiedServiceApiList = getServiceApiList(APPID, SERVICEID);
        log.info("指定服务的接口列表个数：{}" , specifiedServiceApiList.size());
        //转成Map
        Map<String, List<Object>> specifiedServiceApiMap = specifiedServiceApiList.stream().collect(Collectors.groupingBy(item -> ((JSONObject) item).getStr("path")));

        // Step 3: 读取待授权接口列表
        Set<String> pendingApiList = readPendingApiListFromConfigFile();

        // Step 4: 判断待授权接口是否已经授权
        JSONArray unauthorizedApiList = new JSONArray();
        for (String api : pendingApiList) {
            if (!authorizedApiMap.containsKey(api)) {
                if (specifiedServiceApiMap.containsKey(api)) {
                    //判断是否重复增加
                    unauthorizedApiList.addAll(specifiedServiceApiMap.get(api));
                } else {
                    log.info("待授权接口未在指定服务中：" + api);
                }
            }
        }
        log.info("待授权的接口个数：{}" , unauthorizedApiList.size());
        if (unauthorizedApiList.size() > 0) {
            // Step 5: 调用授权接口授权
            authorizeApis(authorizedApiList, unauthorizedApiList);
        }
    }

    private static JSONArray getAuthorizedApiList(String appId) {
        String url = buildUrl(GET_AUTHORIZED_API_LIST_PATH);
        JSONObject requestJson = new JSONObject();
        requestJson.put("appIdList", ListUtil.of(new JSONObject().put("appid", appId)));
        String s = HttpUtil.createPost(url).body(requestJson.toString()).headerMap(getHeaders(),true).execute().body();
        JSONObject responseJson = JSONUtil.parseObj(s);
        JSONArray data = responseJson.getJSONArray("data");
        // 解析响应，获取已授权接口列表
        return data;
    }

    private static Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("Cookie", COOKIE);
        return headers;
    }

    private static JSONArray getServiceApiList(String appId, String serviceId) {
        String url = buildUrl(GET_SERVICE_API_LIST_PATH);
        JSONObject requestJson = new JSONObject();
        requestJson.put("page", 1);
        requestJson.put("limit", 1500);
        requestJson.put("applicationId", appId);
        requestJson.put("serviceId", serviceId);
        String s = HttpUtil.createPost(url).body(requestJson.toString()).headerMap(getHeaders(),true).execute().body();
        JSONObject responseJson = JSONUtil.parseObj(s);
        JSONArray data = responseJson.getJSONArray("data");
        // 解析 response 获取指定服务的接口列表
        return data;
    }

    private static Set<String> readPendingApiListFromConfigFile() {
        // 从配置文件中读取待授权接口列表
        List<String> pendingApiList = FileUtil.readUtf8Lines(AutoAuthorizationHutool.class.getResource("/api.txt"));
        //转成小写
        return pendingApiList.stream().map(String::toLowerCase).collect(Collectors.toSet());
    }

    private static void authorizeApis(JSONArray authorizedApiList, JSONArray unauthorizedApiList) {
        String url = buildUrl(AUTHORIZE_APIS_PATH);
        JSONObject requestJson = new JSONObject();
        // 构建授权接口参数
        JSONArray apiIdList = new JSONArray();
        apiIdList.addAll(authorizedApiList);
        apiIdList.addAll(unauthorizedApiList);
        requestJson.put("apiIdList", apiIdList);
        // 构建已授权接口列表
        requestJson.put("appIdList", ListUtil.of(new JSONObject().put("appid", APPID)));
        requestJson.put("preApiList", authorizedApiList);
        // 调用授权接口进行授权
        String s = HttpUtil.createPost(url).body(requestJson.toString()).headerMap(getHeaders(),true).execute().body();
        log.info("授权接口响应：{}", s);
    }

    private static String buildUrl(String path) {
        return HOST_MAP.get(PROFILE) + path;
    }
}

